/**
 * Created by ss on 16/4/10.
 */
var $ = require('jquery');
var init = require('../util/init.js');
var util = require('../util/util.js');
var templateUtil = require('../util/templateUtil.js');
var positionTpl = require('../../tpl/position.tpl');
var mapUtil = require('../util/mapUtil.js');
require('../../scss/map.scss');

init.init();
var urlGet = util.urlGet();
var value = urlGet.value;
if(value) {
    $("#destination").val(decodeURIComponent(value));
}
var map = mapUtil.init('baiduMap', 18, urlGet.longitude, urlGet.latitude);
var map1 = mapUtil.init('baiduMap1', 18);
var autoObj = mapUtil.searchInit("destination1", function (data) {
    var resultData = data.wr;
    if(resultData.length) {
        render(resultData);
    } else {
        render([]);
    }
});

var render = function (data) {
    $("#resultList").html(templateUtil.template(positionTpl, {
        list: data
    }));
};
$("#destination").on('focus', function () {
    var position = $("#destination").val();
    if(position) {
        $(this).val("");
    }
});

$("#destination").on('input', function () {
    var position = $("#destination").val();
    if(!position) {
        render([]);
        return false;
    }
    mapUtil.search(autoObj, position);
});
$("#returnButton").click(function () {
    util.back();
});
$("#resultList").on("click", "li", function () {
    var value = $(this).html();
    var dom = util.showLoading();
    var local = new BMap.LocalSearch(map, { //智能搜索
        onSearchComplete: function () {
            dom.remove();
            try{
                var pp = local.getResults().getPoi(0).point;
                var object = {
                    address: value,
                    longitude: pp.lng,
                    latitude: pp.lat
                };
                localStorage.setItem(urlGet.type, JSON.stringify(object));
                util.changePage("./addSend");
            }catch(e){
                alert("该地址已失效，请选择其他地址。");
            }

        }
    });
    local.search(value);
});




